<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑小区' : '新增小区'"
    width="800px"
    :before-close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      @submit.prevent
    >
      <el-form-item label="小区名称" prop="communityName">
        <el-input
          v-model="formData.communityName"
          placeholder="请输入小区名称"
          maxlength="50"
          show-word-limit
        />
      </el-form-item>
      
      
      <el-form-item label="所属区域" prop="regionId">
        <div class="region-tree-select-container" style="position: relative;">
          <!-- 自定义下拉区域树选择器 -->
          <el-input
            v-model="selectedRegionName"
            placeholder="请选择所属区域"
            readonly
            @click="showDropdown = true"
            :suffix-icon="showDropdown ? 'ArrowUp' : 'ArrowDown'"
            class="region-select-input"
          />
          <div
            v-if="showDropdown"
            class="custom-region-dropdown"
            ref="dropdownRef"
            @mousedown.stop
          >
            <el-tree
              :data="regionTreeData"
              :props="treeProps"
              lazy
              :load="loadRegionChildren"
              node-key="id"
              highlight-current
              :expand-on-click-node="false"
              @node-click="handleCustomNodeClick"
              ref="regionTreeRef"
            />
          </div>
          <!-- 选中区域路径显示 -->
          <div v-if="selectedRegionPath.length > 0" class="selected-region-path">
            <div class="path-label">已选择区域路径：</div>
            <div class="path-content">
              <el-tag 
                v-for="(region, index) in selectedRegionPath" 
                :key="region.id"
                :type="getRegionTypeTagType(region.regionType) as any"
                size="small"
                class="path-tag"
              >
                {{ region.regionName }}
                <el-icon v-if="index < selectedRegionPath.length - 1" class="path-arrow">
                  <ArrowRight />
                </el-icon>
              </el-tag>
            </div>
          </div>
        </div>
      </el-form-item>
      
      <el-form-item label="物业公司" prop="propertyCompanyId">
        <el-select
          v-model="formData.propertyCompanyId"
          placeholder="请选择物业公司"
          class="property-company-select"
          :loading="propertyCompaniesLoading"
          clearable
        >
          <el-option
            v-for="company in propertyCompanies"
            :key="company.id"
            :label="company.propertyCompanyName"
            :value="company.propertyCompanyId"
          >
            <div class="company-option">
              <span class="company-name">{{ company.propertyCompanyName }}</span>
              <span class="company-code">({{ company.propertyCompanyCode }})</span>
            </div>
          </el-option>
        </el-select>
      </el-form-item>
      
      <el-form-item label="小区地址" prop="address">
        <el-input
          v-model="formData.address"
          placeholder="请输入小区地址"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
      
      <el-form-item label="联系电话" prop="contactPhone">
        <el-input
          v-model="formData.contactPhone"
          placeholder="请输入联系电话"
          maxlength="20"
        />
      </el-form-item>
      
      <el-form-item label="负责人" prop="managerName">
        <el-input
          v-model="formData.managerName"
          placeholder="请输入负责人姓名"
          maxlength="50"
          show-word-limit
        />
      </el-form-item>
      
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio :value="1">启用</el-radio>
          <el-radio :value="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          placeholder="请输入备注信息"
          :rows="3"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
/**
 * 小区信息编辑表单
 * @author Wu.Liang
 * @date 2024-12-21
 * @updated 2025-01-30 - 优化区域树选择功能
 */
import { ref, computed, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Location, 
  OfficeBuilding, 
  Position, 
  MapLocation, 
  ArrowRight 
} from '@element-plus/icons-vue'
import { useRegionStore } from '@/store/region'
import { useUserStore } from '@/store/user'
import { communityApi } from '@/api/community'
import { regionApi } from '@/api/region'
import { communityFormRules } from '@/types/region'
import { onMounted, onBeforeUnmount } from 'vue'
import { showSuccess, showError } from '@/utils/message'

// 定义props
interface Props {
  visible: boolean
  formData?: any
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  formData: null
})

// 定义emits
const emit = defineEmits<{
  'update:visible': [value: boolean]
  'success': []
}>()

// 状态管理
const regionStore = useRegionStore()
const userStore = useUserStore()

// 响应式数据
const formRef = ref()
const regionTreeSelectRef = ref()
const loading = ref(false)
const regionTreeData = ref<any[]>([])
const selectedRegionPath = ref<any[]>([])
const showDropdown = ref(false)
const selectedRegionName = ref<string | undefined>('')
const regionTreeRef = ref()
const dropdownRef = ref()

// 物业公司相关数据
const propertyCompanies = ref<any[]>([])
const propertyCompaniesLoading = ref(false)


// 表单数据
const formData = ref({
  communityName: '',
  regionId: undefined as number | undefined,
  propertyCompanyId: undefined as number | undefined,
  address: '',
  contactPhone: '',
  managerName: '',
  status: 1,
  remark: ''
})

// 表单验证规则
const formRules = communityFormRules

// 树形组件配置
const treeProps = {
  children: 'children',
  label: 'regionName',
  value: 'id',
  hasChildren: 'hasChildren'
}

// 计算属性
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

const isEdit = computed(() => !!props.formData?.id)

// 区域类型映射
const regionTypeMap: Record<string, { text: string; type: string; icon: string }> = {
  '1': { text: '省', type: 'primary', icon: 'Location' },
  '2': { text: '市', type: 'success', icon: 'OfficeBuilding' },
  '3': { text: '区县', type: 'warning', icon: 'Position' },
  '4': { text: '街道', type: 'info', icon: 'MapLocation' },
  '5': { text: '小区', type: 'danger', icon: 'Location' }
}

// 获取区域类型文本
const getRegionTypeText = (type: number) => {
  return regionTypeMap[String(type)]?.text || '未知'
}

// 获取区域类型标签样式
const getRegionTypeTagType = (type: number) => {
  return regionTypeMap[String(type)]?.type || 'info'
}

// 获取区域类型图标
const getRegionTypeIcon = (type: number) => {
  const iconName = regionTypeMap[String(type)]?.icon || 'Location'
  return iconName
}

// 获取区域类型图标样式
const getRegionTypeIconClass = (type: number) => {
  return `region-icon-${type}`
}

// 重置表单
const resetForm = () => {
  formData.value = {
    communityName: '',
    regionId: undefined,
    propertyCompanyId: undefined,
    address: '',
    contactPhone: '',
    managerName: '',
    status: 1,
    remark: ''
  }
  selectedRegionPath.value = []
  formRef.value?.clearValidate()
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    
    loading.value = true
    
    // 构建提交数据，确保包含必需的字段并正确映射字段名
    const submitData = {
      communityName: formData.value.communityName,
      regionId: formData.value.regionId,
      propertyCompanyId: formData.value.propertyCompanyId,
      address: formData.value.address,
      contactPhone: formData.value.contactPhone,
      managerName: formData.value.managerName,
      remark: formData.value.remark,
      status: formData.value.status,
      latitude: 0, // 默认值
      longitude: 0 // 默认值
    }
    
    if (isEdit.value) {
      await communityApi.updateCommunity(props.formData.id, submitData)
    } else {
      await communityApi.createCommunity(submitData)
    }
    
    emit('success')
    handleClose()
    showSuccess('保存成功')
  } catch (error) {
    if (error !== false) {
      showError('保存失败')
    }
  } finally {
    loading.value = false
  }
}

// 加载物业公司数据
const loadPropertyCompanies = async () => {
  try {
    propertyCompaniesLoading.value = true
    await userStore.getUserPropertyCompanies()
    // 从userStore获取物业公司列表
    const companyList = userStore.companyList
    if (companyList && companyList.length > 0) {
      propertyCompanies.value = companyList.map((company: any) => ({
        id: company.id,
        propertyCompanyId: company.id,
        propertyCompanyName: company.name,
        propertyCompanyCode: company.code
      }))
      // 默认选中第一个物业公司
      if (!formData.value.propertyCompanyId) {
        formData.value.propertyCompanyId = propertyCompanies.value[0].propertyCompanyId
      }
    }
  } catch (error) {
    console.error('加载物业公司列表失败:', error)
  } finally {
    propertyCompaniesLoading.value = false
  }
}


// 加载区域树数据
const loadRegionTree = async () => {
  try {
    const response = await regionApi.getRegionTree()
    if (response.code === 200 && response.data) {
      regionTreeData.value = response.data
    } else {
      showError('加载区域列表失败')
    }
  } catch (error) {
    showError('加载区域列表失败')
  }
}

// 加载区域路径
const loadRegionPath = async (regionId: number) => {
  try {
    const response = await regionApi.getRegionPath(regionId)
    if (response.code === 200 && response.data) {
      selectedRegionPath.value = response.data
    }
  } catch (error) {
    console.error('加载区域路径失败:', error)
  }
}

// 展开到选中的区域
const expandToSelectedRegion = async (regionId: number) => {
  try {
    // 获取区域路径
    const response = await regionApi.getRegionPath(regionId)
    if (response.code === 200 && response.data) {
      selectedRegionPath.value = response.data
      
      // 逐级展开区域树
      for (const region of response.data) {
        if (region.id !== regionId) {
          await expandRegionNode(region.id)
        }
      }
      
      // 设置选中值
      nextTick(() => {
        formData.value.regionId = regionId
      })
    }
  } catch (error) {
    console.error('展开到选中区域失败:', error)
  }
}

// 展开区域节点
const expandRegionNode = async (parentId: number) => {
  try {
    const response = await regionApi.getRegionTree(parentId)
    if (response.code === 200 && response.data) {
      // 更新树数据中的子节点
      updateTreeNodeChildren(regionTreeData.value, parentId, response.data)
    }
  } catch (error) {
    console.error('展开区域节点失败:', error)
  }
}

// 更新树节点子节点
const updateTreeNodeChildren = (nodes: any[], parentId: number, children: any[]) => {
  for (const node of nodes) {
    if (node.id === parentId) {
      node.children = children
      node.hasChildren = children.length > 0
      break
    }
    if (node.children && node.children.length > 0) {
      updateTreeNodeChildren(node.children, parentId, children)
    }
  }
}

// 懒加载子区域
const loadRegionChildren = async (node: any, resolve: (children: any[]) => void) => {
  const parentId = node.level === 0 ? 0 : node.data.id
  try {
    const response = await regionApi.getRegionTree(parentId)
    if (response.code === 200 && response.data) {
      resolve(response.data)
    } else {
      resolve([])
    }
  } catch {
    resolve([])
  }
}

// 自定义节点点击逻辑
const handleCustomNodeClick = async (data: any, node: any, comp: any) => {
  if (data.hasChildren) {
    if (!data.children || data.children.length === 0) {
      await new Promise<void>(resolve => {
        node.expand(async () => {
          if (!data.children || data.children.length === 0) {
            formData.value.regionId = data.id
            selectedRegionName.value = data.regionName
            showDropdown.value = false
            await loadRegionPath(data.id)
          }
          resolve()
        })
      })
      return
    }
    return
  }
  formData.value.regionId = data.id
  selectedRegionName.value = data.regionName
  showDropdown.value = false
  await loadRegionPath(data.id)
}

// 点击外部关闭下拉
const handleClickOutside = (event: MouseEvent) => {
  if (!dropdownRef.value) return
  const inputEl = regionTreeSelectRef?.value?.$el || null
  if (
    !dropdownRef.value.contains(event.target) &&
    (!inputEl || !inputEl.contains(event.target))
  ) {
    showDropdown.value = false
  }
}

// 监听表单数据变化
watch(() => props.formData, (newData) => {
  if (newData) {
    formData.value = { ...newData }
    // 编辑模式下，加载区域路径
    if (newData.regionId) {
      loadRegionPath(newData.regionId)
    }
  } else {
    resetForm()
  }
}, { immediate: true })

// 监听弹窗显示状态
watch(() => props.visible, async (visible) => {
  if (visible) {
    await loadRegionTree()
    await loadPropertyCompanies()
    if (isEdit.value && props.formData?.regionId) {
      // 编辑模式下，展开到选中的区域
      await expandToSelectedRegion(props.formData.regionId)
    }
  }
})

// 选中区域回显
watch(() => formData.value.regionId, async (newVal) => {
  if (newVal) {
    await loadRegionPath(newVal)
    // 路径最后一个就是当前选中
    if (selectedRegionPath.value.length > 0) {
      selectedRegionName.value = selectedRegionPath.value[selectedRegionPath.value.length - 1].regionName
    }
  } else {
    selectedRegionName.value = ''
  }
}, { immediate: true })
onMounted(() => {
  document.addEventListener('mousedown', handleClickOutside)
})
onBeforeUnmount(() => {
  document.removeEventListener('mousedown', handleClickOutside)
})
</script>

<style lang="scss" scoped>
.dialog-footer {
  text-align: right;
}

.region-tree-select-container {
  .region-tree-node {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    
    .node-content {
      display: flex;
      align-items: center;
      flex: 1;
      
      .node-icon {
        margin-right: 8px;
        font-size: 16px;
        
        &.region-icon-1 { color: #409eff; } // 省
        &.region-icon-2 { color: #67c23a; } // 市
        &.region-icon-3 { color: #e6a23c; } // 区县
        &.region-icon-4 { color: #909399; } // 街道
        &.region-icon-5 { color: #f56c6c; } // 小区
      }
      
      .node-label {
        margin-right: 8px;
        font-weight: 500;
      }
    }
    
    .node-actions {
      opacity: 0;
      transition: opacity 0.3s;
    }
    
    &:hover .node-actions {
      opacity: 1;
    }
  }
}

.selected-region-path {
  margin-top: 8px;
  padding: 8px 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
  
  .path-label {
    font-size: 12px;
    color: #909399;
    margin-bottom: 4px;
  }
  
  .path-content {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 4px;
    
    .path-tag {
      display: flex;
      align-items: center;
      
      .path-arrow {
        margin-left: 4px;
        font-size: 12px;
        color: #909399;
      }
    }
  }
}

:deep(.el-tree-select) {
  .el-tree-node__content {
    padding: 8px 0;
  }
  
  .el-tree-node__expand-icon {
    font-size: 12px;
  }
}

.custom-region-dropdown {
  position: absolute;
  z-index: 9999;
  left: 0;
  top: 40px;
  width: 100%;
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  max-height: 400px;
  overflow-y: auto;
  padding: 8px 0;
}

/* 下拉框宽度优化 */
.region-select-input,
.property-company-select {
  width: 100% !important;
  min-width: 200px;
}

/* 确保表单项有足够的空间 */
:deep(.el-form-item__content) {
  min-width: 0;
  flex: 1;
}

/* 优化下拉选项显示 */
.company-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  
  .company-name {
    flex: 1;
    font-weight: 500;
  }
  
  .company-code {
    color: #909399;
    font-size: 12px;
    margin-left: 8px;
  }
}

</style> 